"""主窗口模块 - PyQt5版本"""
import sys
import os

ROOT_DIR = os.path.join(os.path.dirname(__file__), '..', '..')
sys.path.insert(0, ROOT_DIR)

from PyQt5.QtWidgets import (QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, 
                             QLabel, QStatusBar, QApplication, QSplitter, 
                             QFrame, QSizePolicy)
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont

from app.gui.views.connection_view import ConnectionView
from app.gui.views.download_view import DownloadView
from app.gui.controllers.main_controller import MainController


class MainWindow(QMainWindow):
    """主窗口类 - PyQt5版本"""
    
    def __init__(self):
        super().__init__()
        
        self._controller = MainController(self)
        self._connection_view = None
        self._download_view = None
        self._status_label = None
        
        self._setup_window()
        self._create_widgets()
        self._setup_controller()
        
    def _setup_window(self):
        """设置窗口属性"""
        self.setWindowTitle("Bootloader By Can")
        
        window_width = 900
        window_height = 750
        
        screen = QApplication.primaryScreen()
        screen_geometry = screen.geometry()
        screen_width = screen_geometry.width()
        screen_height = screen_geometry.height()
        
        x = (screen_width - window_width) // 2
        y = (screen_height - window_height) // 2
        
        self.setGeometry(x, y, window_width, window_height)
        self.setMinimumSize(700, 600)
            
    def _create_widgets(self):
        """创建界面组件"""
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        main_layout = QVBoxLayout()
        main_layout.setSpacing(10)
        main_layout.setContentsMargins(15, 10, 15, 10)
        central_widget.setLayout(main_layout)
        
        title_widget = self._create_title_section()
        main_layout.addWidget(title_widget)
        
        splitter = QSplitter(Qt.Vertical)
        main_layout.addWidget(splitter)
        
        self._connection_view = ConnectionView()
        self._connection_view.setMaximumHeight(250)
        splitter.addWidget(self._connection_view)
        
        self._download_view = DownloadView()
        splitter.addWidget(self._download_view)
        
        splitter.setSizes([250, 500])
        
        self._create_status_bar()
        
    def _create_title_section(self):
        """创建标题区域"""
        widget = QWidget()
        layout = QHBoxLayout()
        widget.setLayout(layout)
        
        title_label = QLabel("固件下载工具(CAN通信)")
        title_font = QFont()
        title_font.setPointSize(14)
        title_font.setBold(True)
        title_label.setFont(title_font)
        title_label.setStyleSheet("color: #2c3e50; margin: 5px 0px;")
        layout.addWidget(title_label)
        
        layout.addStretch()
        
        version_label = QLabel("v1.0.0")
        version_font = QFont()
        version_font.setPointSize(9)
        version_label.setFont(version_font)
        version_label.setStyleSheet("color: #7f8c8d; margin: 5px 0px;")
        layout.addWidget(version_label)
        
        separator = QFrame()
        separator.setFrameShape(QFrame.HLine)
        separator.setFrameShadow(QFrame.Sunken)
        separator.setStyleSheet("color: #bdc3c7;")
        
        container = QWidget()
        container_layout = QVBoxLayout()
        container_layout.setContentsMargins(0, 0, 0, 0)
        container_layout.setSpacing(5)
        container_layout.addWidget(widget)
        container_layout.addWidget(separator)
        container.setLayout(container_layout)
        
        return container
        
    def _create_status_bar(self):
        """创建状态栏"""
        status_bar = QStatusBar()
        self.setStatusBar(status_bar)
        
        self._status_label = QLabel("就绪")
        self._status_label.setStyleSheet("padding: 2px 5px; color: #34495e;")
        status_bar.addWidget(self._status_label)
        
        copyright_label = QLabel("© 2025 Fasteur Team")
        copyright_label.setStyleSheet("padding: 2px 10px; color: #95a5a6;")
        status_bar.addPermanentWidget(copyright_label)
        
    def _setup_controller(self):
        """设置控制器"""
        self._controller.set_views(self._connection_view, self._download_view)
        
    def closeEvent(self, event):
        """窗口关闭事件"""
        try:
            if self._controller:
                self._controller.cleanup()
        except Exception as e:
            print(f"清理资源时出错: {e}")
        finally:
            event.accept()
            
    def update_status(self, message):
        """更新状态栏消息"""
        if self._status_label:
            self._status_label.setText(message)


def main():
    """主函数"""
    try:
        app = QApplication(sys.argv)
        
        app.setApplicationName("Bootloader By Can")
        app.setApplicationVersion("1.0.0")
        app.setOrganizationName("OpenBLT Team")
        
        app.setStyle('Fusion')
        
        window = MainWindow()
        window.show()
        
        print("PyQt5 GUI应用程序已启动")
        print("标题: Bootloader By Can")
        print("基于MVC架构设计")
        print("="*50)
        
        sys.exit(app.exec_())
        
    except ImportError as e:
        print(f"导入模块失败: {e}")
        print("请确保已安装PyQt5: pip install PyQt5")
        sys.exit(1)
    except Exception as e:
        print(f"启动应用程序失败: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)


if __name__ == "__main__":
    main()